﻿using Flashlight.Mvvm.Common;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.PubSubEvents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Flashlight.Mvvm.ViewModels
{
    public class MainPageViewModel : ViewModel, Flashlight.Mvvm.ViewModels.IMainPageViewModel
    {
        IEventAggregator _eventAggregator = default(IEventAggregator);
        Services.ILightService _lightService = default(Services.ILightService);
        Factories.ILightFactory _lightFactory = default(Factories.ILightFactory);
        public MainPageViewModel(Services.ILightService lightService, IEventAggregator eventAggregator, Factories.ILightFactory lightFactory)
        {
            this._lightFactory = lightFactory;
            this._lightService = lightService;
            this._eventAggregator = eventAggregator;
            this.Light = this._lightFactory.Create();
        }

        public override void OnNavigatedTo(object navigationParameter, Windows.UI.Xaml.Navigation.NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            this._eventAggregator.GetEvent<Messages.ToggleLight>().Subscribe(HandleToggleLight);
        }

        Models.Light _Light = default(Models.Light);
        public Models.Light Light { get { return _Light; } set { SetProperty(ref _Light, value); } }

        private void HandleToggleLight(States state)
        {
            switch (state)
            {
                case States.On:
                    this._lightService.TurnOn();
                    break;
                case States.Off:
                    this._lightService.TurnOff();
                    break;
            }
        }

        DelegateCommand _ToggleLightCommand = null;
        public DelegateCommand ToggleLightCommand
        {
            get
            {
                if (_ToggleLightCommand != null)
                    return _ToggleLightCommand;
                _ToggleLightCommand = new DelegateCommand
                (
                    () => { this.Light.State = (this.Light.State == States.On) ? States.Off : States.On; },
                    () => { return true; }
                );
                this.PropertyChanged += (s, e) => _ToggleLightCommand.RaiseCanExecuteChanged();
                return _ToggleLightCommand;
            }
        }
    }
}
